import {useRef} from 'react'
import {Box} from '@react-three/drei'
import {useControls} from 'leva'
import {useFrame} from '@react-three/fiber'

const Light = (props) => {
  const {
    position = [0, 0, 0],
    intensity = 3,
    distance = 15,
    decay = 3,
    color = '#4124c9',
    visible = false
  } = props
  return (
    <>
      <group position={position}>
        <pointLight
          intensity={intensity}
          distance={distance}
          decay={decay}
          color={color}
        />
        <Box scale={0.1} visible={visible}>
          <meshBasicMaterial color="white"/>
        </Box>
      </group>
    </>
  )
}

export const CustomLight = ({children}) => {
  const animatedLightRef = useRef()
  const shadowBias = -0.005
  const shadowMapSize = 2048


  const {x, y, z} = useControls({
    x: {value: 8.5, min: -10, max: 10, step: 0.1},
    y: {value: 2.5, min: -10, max: 10, step: 0.1},
    z: {value: -1.2, min: -10, max: 10, step: 0.1}
  })

  useFrame(({clock}) => {
    animatedLightRef.current.position.x =
      Math.sin(clock.getElapsedTime() * 0.5) * 2
  })

  return (
    <>
      <directionalLight position={[6, 4, 6]} intensity={0.4} color="white"/>
      <group scale={0.66}>
        {children}
        <Light
          // position={[x, y, z]}
          position={[7.6, 1.4, 0.7]}
          visible={false}
        />
        <Light
          position={[-5.3, 1.5, 5.4]}
          visible={false}
        />

        <Light
          position={[5.5, 0.5, -1.2]}
          intensity={3}
          distance={15}
          decay={3}
          color="#4124c9" // blue
          visible={false}
        />

        <Light
          position={[-3, 3, -2]}
          intensity={3}
          decay={3}
          distance={6}
          color="#a5adff" // blue
          visible={false}
        />

        <group position={[0, 2.5, 0.5]} ref={animatedLightRef}>
          <pointLight
            intensity={0.9}
            decay={2}
            distance={10}
            castShadow
            color="#f7d216" // Orange
            shadow-bias={shadowBias}
            shadow-mapSize-width={shadowMapSize}
            shadow-mapSize-height={shadowMapSize}
          />
          <Box scale={0.1} visible={false}>
            <meshBasicMaterial color="white"/>
          </Box>
        </group>
      </group>
    </>
  )

}
